package com.ds.robot.assistant.component;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.ds.robot.assistant.entity.ReqMilestonesEntity;
import com.ds.robot.assistant.enums.MilestoneType;
import com.ds.robot.assistant.enums.TimePoint;
import com.ds.robot.assistant.model.MilestoneData;
import com.ds.robot.assistant.service.ReqMilestonesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 作用：
 * 注意：上传Excel时每次只上传一个项目的数据
 *
 * @author WeiShaoying
 * 
 */
@Slf4j
public class MilestoneReadListener implements ReadListener<MilestoneData> {

    private static final int BATCH_COUNT = 10;

    private final ReqMilestonesService milestonesService;

    private boolean first = true;

    /**
     * 缓存的数据
     */
    private List<MilestoneData> cachedList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public MilestoneReadListener(ReqMilestonesService milestonesService) {
        this.milestonesService = milestonesService;
    }


    @Override
    public void invoke(MilestoneData milestoneData, AnalysisContext analysisContext) {
        log.info("解析数据: {}", JSON.toJSONString(milestoneData));
        if (first) {
            if (milestonesService.checkDataExist(milestoneData)) {
                throw new RuntimeException("[" + milestoneData.getReqName() + "]数据已存在");
            }
            first = false;
        }
        cachedList.add(milestoneData);
        // 批处理
        if (cachedList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理List 防止OOM
            cachedList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("Excel所有数据解析完成");
    }


    @Transactional(rollbackFor = Exception.class)
    public void saveData() {
        if (!CollectionUtils.isEmpty(cachedList)) {
            List<ReqMilestonesEntity> list = cachedList.stream().map(data -> {
                ReqMilestonesEntity entity = new ReqMilestonesEntity();
                BeanUtils.copyProperties(data, entity);
                entity.setReqId(0);
                entity.setReminderUser(data.getReminderUser().replace('，', ','));
                // 改为下拉框，传递的是文本
                entity.setMilestoneType(MilestoneType.getValueByDescription(data.getMilestoneType()));
                entity.setTimePoint(TimePoint.getValueByDescription(data.getTimePoint()));

                if (!StringUtils.hasText(data.getReminderMessage())) {
                    // entity.setReminderMessage(MilestoneType.getDescriptionByValue(data.getMilestoneType()));
                    entity.setReminderMessage(data.getMilestoneType());
                }
                if (!StringUtils.hasText(data.getNotes())) {
                    // entity.setNotes(TimePoint.getDescriptionByValue(data.getTimePoint()));
                    entity.setNotes(data.getTimePoint());
                }
                return entity;
            }).collect(Collectors.toList());
            milestonesService.saveBatch(list);
        }
        log.info("保存{}条数据成功", cachedList.size());
    }

}
